var standard_tablistwm_cache = {};
var standard_tablistwm = {

    init: function() {

        var that = this,
            token = $.cookie('token');



        //新增标书
        $('[data-name="addItem"]').click(function() {
            if ($("#addItem").length > 0) {
                $("#addItem").show();
            } else {
                var $addItemTpl = $("#addItemTplwm");
                $("#myTabContent").append($addItemTpl.html());
            }

            $("#myTabContent .tab-pane").removeClass('active in');

            //提交新增标书
            standard_addwm.init();
        });

        that.getList();
        that.editAction();
       
    },
    getList:function(){
        var that = this,
            token = $.cookie('token');
            $.ajaxSettings.global=false;
             $.ajaxSend('api/BidBase/GetBidList?token=' + token, {

        }, function(redata) {
        	if(redata.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;
            }
            if (redata.recode == '0000') {
                var compiled = _.template($("#listTplwm").html());
                var odata = redata.mod;
                // alert(that.format(odata[0].start_bid_time))
                for (var i = 0, length = odata.length; i < length; i++) {
                    odata[i].start_bid_time = that.format(odata[i].start_bid_time);
                    odata[i].end_bid_time = that.format(odata[i].end_bid_time);
                }
                $("#tabConwm").html(compiled(redata.mod));


        

            }
        });
             $.ajaxSettings.global=true;

    },
    editAction:function(){
        var that = this;

        $("#editItemBtn").on("click", function(){
            var _billid = $("input[name='inputBid']:checked").attr("data-billid");
            if(!$("input[name='inputBid']:checked").attr("data-billid")){
                alert('请选中需要修改的列表！')
                return;
            }

            $("#dataTitle").html("修改标单")
            $('#editItemModelwm').modal('show')
       // })
               //  $('#editItemModelwm').on('show.bs.modal', function(event) {  //修改
            getEditData(_billid,true);     
                   
        });

        $("#standard_tablistwm").on("click", '.j_look', function(){
            var billid = $(this).attr('billid');
            $("#dataTitle").html("标单详情")
            $('#editItemModelwm').modal('show')
            getEditData(billid,false);
        })

        function getEditData(id, bool){
             var button = $(event.relatedTarget),
                        billid = button.data('billid');
 
                        $.ajax({  
                                  url: COMMONURL + "api/BidBase/GetBillMod?token=" + $.cookie('token')+'&billid='+id,
                                  type: "post",
                                  data: {
                                     
                                  }
                              }).done(function(redata) {
                              	  if(redata.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;
            }
                                            if(redata.recode == '0000'){  //edititemTmp

                                              var value = redata.mod;

                                              value.consignee_time=that.formatTime(value.consignee_time);
                                              value.receipt_time=that.formatTime(value.receipt_time);
                                              value.start_bid_time=that.formatTime(value.start_bid_time);
                                              value.end_bid_time = that.formatTime(value.end_bid_time);
                                              value.bool=bool;
                                              var compiled = _.template($("#edititemTmpwm").html());
                                              $("#edititemFormwm").html(compiled(value));

                                            
                                              var StartcityIdArray = value.start_city_id_x ? value.start_city_id_x.split('|') : [];
                                              var StartareaId = StartcityIdArray[0] == undefined ? '' : StartcityIdArray[0];
                                              var StartcityId = StartcityIdArray[1] == undefined ? '' : StartcityIdArray[1];
                                              var StarttownId = StartcityIdArray[2] == undefined ? '' : StartcityIdArray[2];

                                              var EndcityIdArray = value.end_city_id_x ? value.end_city_id_x.split('|') : [];
                                              var EndareaId = EndcityIdArray[0] == undefined ? '' : EndcityIdArray[0];
                                              var EndcityId = EndcityIdArray[1] == undefined ? '' : EndcityIdArray[1];
                                              var EndtownId = EndcityIdArray[2] == undefined ? '' : EndcityIdArray[2];

                                              that.getAddress({
                                                    type: 10
                                                }, $("#editend_pro_id"), function() {
                                                    if (EndareaId != '') {

                                                        $("#editend_pro_id option").each(function(i, t) {
                                                            if ($(t).attr('data-id') == EndareaId) {

                                                                $(t).attr('selected', true);
                                                            }
                                                        })
                                                    }

                                                    that.getAddress({
                                                        type: 20,
                                                        sub_city_id: EndareaId
                                                    }, $("#editend_city_id"), function() {
                                                        if (EndcityId != '') {
                                                            $("#editend_city_id option").each(function(i, t) {
                                                                if ($(t).attr('data-id') == EndcityId) {
                                                                    $(t).attr('selected', true);
                                                                }
                                                            })
                                                        }

                                                        that.getAddress({
                                                            type: 30,
                                                            sub_city_id: EndcityId
                                                        }, $("#editend_town_id"), function() {
                                                            if (EndtownId != '') {
                                                                $("#editend_town_id option").each(function(i, t) {
                                                                    if ($(t).attr('data-id') == EndtownId) {
                                                                        $(t).attr('selected', true);
                                                                    }
                                                                })
                                                            }

                                                        });
                                                    });
                                                });

                                                that.getAddress({
                                                    type: 10
                                                }, $("#editstart_pro_id"), function() {
                                                    if (StartareaId != '') {
                                                        $("#editstart_pro_id option").each(function(i, t) {
                                                            if ($(t).attr('data-id') == StartareaId) {

                                                                $(t).attr('selected', true);
                                                            }
                                                        })
                                                    }

                                                    that.getAddress({
                                                        type: 20,
                                                        sub_city_id: StartareaId
                                                    }, $("#editstart_city_id"), function() {
                                                        if (StartcityId != '') {
                                                            $("#editstart_city_id option").each(function(i, t) {
                                                                if ($(t).attr('data-id') == StartcityId) {
                                                                    $(t).attr('selected', true);
                                                                }
                                                            })
                                                        }

                                                        that.getAddress({
                                                            type: 30,
                                                            sub_city_id: StartcityId
                                                        }, $("#editstart_town_id"), function() {
                                                            if (StarttownId != '') {
                                                                $("#editstart_town_id option").each(function(i, t) {
                                                                    if ($(t).attr('data-id') == StarttownId) {
                                                                        $(t).attr('selected', true);
                                                                    }
                                                                })
                                                            }

                                                        });
                                                    });
                                                });
                                              
                                            that.changeAddress();
                                            that.getGoodsHour(value.start_receipt_hour,value.end_receipt_hour);
                                            that.dateInit();
                                             that.getStaffList(value.staff_phone);
                                                that.getContactsList(value.contacts_phone);

                                                $('input[name="editdanger"]').click(function(){
                                                        var index = $('input[name="editdanger"]').index($(this))
                                                     if(index==0){
                                                            $('#editwuliu_type option[text=0]').attr('selected','selected');
                                                        }else if(index==1 || index==2){
                                                            $('#editwuliu_type option[text=1]').attr('selected','selected');
                                                     }
                                                 })

                                                that.doSubmit(id);

                                            }
                              });

        }
                
                
    },
    dateInit: function() {
        $('.datepicker').datetimepicker({
            language: 'zh-CN',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            showMeridian: 1,
            format: 'yyyy-mm-dd hh:ii'
        });
    },
    getGoodsHour: function(nS,enS) {
        //取货时间
        var $editstart_receipt_hour = $("#editstart_receipt_hour"),
            $editend_receipt_hour = $("#editend_receipt_hour"),
            default_start = 0;
        default_end = 24;

        initTime(default_start, default_end, $editstart_receipt_hour,nS);
        initTime(default_start, default_end, $editend_receipt_hour,enS);

        $editstart_receipt_hour.change(function() {
            var val = +$(this).val();
            initTime(val + 1, default_end, $editend_receipt_hour);
        });

        $editend_receipt_hour.change(function() {
            var val = +$(this).val();
            initTime(default_start, val, $editstart_receipt_hour);
        });

        function initTime(start, end, $obj, s) {
            var tpl = [];
            for (var i = start; i < end; i++) {
                if(i==s){
                   tpl.push('<option value="' + i + '" selected="selected">' + i + '</option>'); 
               }else{
                tpl.push('<option value="' + i + '">' + i + '</option>');
                }
            }
            $obj.html(tpl.join(""));
        }

    },
    getAddress: function(type, obj, callback) {
        $.ajax({
            url: COMMONURL + 'api/CityBase/GetCityBaseList?token=' + $.cookie('token'),
            type: 'post',
            dataType: 'json',
            data: type

        }).done(function(data) {
            var arry = [];
            if (!!data.mod) {
                if (!data.mod.length) {
                    arry.push('<option value="' + '" data-id="' + '">' + '请选择' + '</option>');
                } else {
                    $.each(data.mod, function(i, v) {
                        arry.push('<option value="' + v.city_name + '" data-id="' + v.city_id + '">' + v.city_name + '</option>');
                    });
                }
    
                obj.html(arry.join(''));
                if (typeof callback == 'function') {
                    callback();
                }
            }

        })
    },
    changeAddress:function(){
            var that = this;
        $("#editstart_pro_id").change(function() {
            var $this = $(this);
            that.getAddress({
                type: 20,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#editstart_city_id"), function() {
                that.getAddress({
                    type: 30,
                    sub_city_id: $("#editstart_city_id option").eq(0).attr('data-id')
                }, $("#editstart_town_id"));
            });
        })

        $("#editstart_city_id").change(function() {
            var $this = $(this);
            that.getAddress({
                type: 30,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#editstart_town_id"));
        })

        $("#editend_pro_id").change(function() {
            var $this = $(this);
            that.getAddress({
                type: 20,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#editend_city_id"), function() {
                that.getAddress({
                    type: 30,
                    sub_city_id: $("#editend_city_id option").eq(0).attr('data-id')
                }, $("#editend_town_id"));
            });
        })

        $("#editend_city_id").change(function() {
            var $this = $(this);
            that.getAddress({
                type: 30,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#editend_town_id"));
        })
    },
    getStaffList: function(phone) {
        $.ajax({
            url: COMMONURL + "api/companysale/get?token=" + $.cookie('token'),
            type: "get",
            dataType: "json"
        }).done(function(redata) {
        	if(redata.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;
            }
            if (redata.recode == '0000') {
                var s = [];
                if (redata.mod) {
                    for (var i = 0; i < redata.mod.length; i++) {
                        if(redata.mod[i].sales_phone==phone){
                            s.push('<option selected="selected" value="'+redata.mod[i].sales_phone+'">' + redata.mod[i].sales_name + '</option>');
                        }else{
                            s.push('<option value="'+redata.mod[i].sales_phone+'">' + redata.mod[i].sales_name + '</option>');
                        }
                        
                    }
                    $("#editstaff").html(s.join(''));
                }
            }
        });
    },
    getContactsList:function(phone){
        $.ajax({
            url: COMMONURL + "api/Account/GetContactsList?token=" + $.cookie('token'),
            type: "post",
            dataType: "json"
        }).done(function(redata) {
        	if(redata.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;
            }
            if (redata.recode == '0000') {
                var s = [];
                if (redata.mod) {
                    for (var i = 0; i < redata.mod.length; i++) {
                        if(redata.mod[i].phone==phone){
                            s.push('<option selected="selected" value="'+redata.mod[i].phone+'">' + redata.mod[i].nick_name + '</option>');
                        }else{
                            s.push('<option value="'+redata.mod[i].phone+'">' + redata.mod[i].nick_name + '</option>');
                        }
                        
                    }
                    $("#editcontacts").html(s.join(''));
                }
            }
        });
    },
    formatTime:function(nS){
        Date.prototype.dateFormat=function(fmt) {         
        var o = {         
            "M+" : this.getMonth()+1, //月份         
            "d+" : this.getDate(), //日         
            "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时         
            "H+" : this.getHours(), //小时         
            "m+" : this.getMinutes(), //分         
            "s+" : this.getSeconds(), //秒         
            "q+" : Math.floor((this.getMonth()+3)/3), //季度         
            "S" : this.getMilliseconds() //毫秒         
        };         
        var week = {         
            "0" : "\u65e5",         
            "1" : "\u4e00",         
            "2" : "\u4e8c",         
            "3" : "\u4e09",         
            "4" : "\u56db",         
            "5" : "\u4e94",         
            "6" : "\u516d"        
        };         
        if(/(y+)/.test(fmt)){         
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));         
        }         
        if(/(E+)/.test(fmt)){         
            fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);         
        }         
        for(var k in o){         
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         
            }
        }
        return fmt;         
    } 
    return new Date(parseInt(nS) * 1000).dateFormat("yyyy-MM-dd HH:mm");
    /*var now = new Date();
    var nowAdd = new Date(now.valueOf()+3*60*60*1000).dateFormat("yyyy-MM-dd HH:mm");
    
     $("#consignee_time").val(nowAdd);
     $("#start_bid_time").val(now.dateFormat("yyyy-MM-dd HH:mm"));*/
    },
    format: function(nS) {
        //return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');
             if(!nS) return null;
            var date = new Date(nS*1000);
            var year = date.getFullYear();
            var month = date.getMonth()+1;
            var d = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            return year+'-'+month+'-'+d+' '+hours+':'+minutes;
    },
    doSubmit: function(_bid) {
       

        $("#edititemFormwm").validate({
            errorClass: 'error',
            rules: {
                editstart_address: "required",
                editconsignee_time: 'required',
                editend_address: "required",
                editreceipt_time: 'required',
                editstart_bid_time: "required",
                //editnumber: "required",
                editinformation:"required",
                editwuliu_type: "required"
              //  start_city_name: "required",
              //  end_city_name: "required"
                    /* end_address2:{
                        isAddress:true
                     }*/
            },
            messages: {
                editstart_address: "",
                editconsignee_time: '',
                editend_address: "",
                editreceipt_time: '',
                editstart_bid_time: "",
                editnumber: "",
                editinformation:"",
                editwuliu_type: ""
               // start_city_name: "",
               // end_city_name: ""
                    /* end_address2:{
                        isAddress:''
                     }*/
            },
            submitHandler: function(form) {
                var editstart_city_id = $.trim($("#editstart_town_id option:selected").attr('data-id')),
                    editstart_city_id_x = $.trim($("#editstart_pro_id option:selected").attr('data-id')) + '|' + $.trim($("#editstart_city_id option:selected").attr('data-id')) + '|' + editstart_city_id,
                    // start_city_name = $("#start_pro_id").val() + '|' + $("#start_city_id").val() + '|' + $("#start_town_id").val(),
                    editstart_city_name =   $("#editstart_pro_id").val()+$("#editstart_city_id").val()+$("#editstart_town_id").val(),
                    editstart_address = $.trim($("#editstart_address").val()),
                    editconsignee_time = $("#editconsignee_time").val(),
                    editend_city_id = $("#editend_town_id option:selected").attr('data-id'),
                    editend_city_id_x = $("#editend_pro_id option:selected").attr('data-id') + "|" + $("#editend_city_id option:selected").attr('data-id') + "|" + editend_city_id,
                    //end_city_name = $("#end_pro_id").val() + '|' + $("#end_city_id").val() + '|' + $("#end_town_id").val(),
                    editend_city_name = $("#editend_pro_id").val()+$("#editend_city_id").val()+$("#editend_town_id").val(),
                    editend_address = $.trim($("#editend_address").val());
                var editend_city_id2 = editend_city_name2 = editend_address2 = editend_city_id2_x = '';
               /* $("#editreceiptAdd [data-name='editaddress_add']").each(function() {
                    var editcity_id = $(this).find('[data-name="edittown"] option:selected').attr('data-id'),
                        editcity_id_x = $(this).find('[data-name="editprovince"] option:selected').attr('data-id') + '|' + $(this).find('[data-name="editcity"] option:selected').attr('data-id') + '|' + city_id,
                      
                        editcity_name = $(this).find('[data-name="editprovince"]').val()+$(this).find('[data-name="editcity"]').val()+$(this).find('[data-name="edittown"]').val(),
                        editaddress = $(this).find('[name="editdetail"]').val();
                    editend_city_id2 = editend_city_id2 + editcity_id + ';';
                    editend_city_name2 = editend_city_name2 + editcity_name + ';';
                    editend_address2 = editend_address2 + editaddress+';';
                    editend_city_id2_x = editend_city_id2_x+editcity_id_x+';';
                });*/
                var editstart_bid_time = $("#editstart_bid_time").val(),
                	bid_id=_bid,
                    editend_bid_time = $('#editendbid_other').val(),
                    editdanger = $('[name="editdanger"]:checked').val(),
                    editwuliu_type = $("#editwuliu_type option:selected").attr("value"),
                    editnumber = $("#editnumber").val(),
                    editinformation = $("#editinformation").val(),
                    editremark = $("#editremark").val(),
                    editstart_receipt_hour = $("#editstart_receipt_hour").val(),
                    editend_receipt_hour = $("#editend_receipt_hour").val(),
                    editreceipt_time = $("#editreceipt_time").val(),
                    editcontacts = $("#editcontacts option:selected").text(),
                    editcontacts_phone = $("#editcontacts option:selected").val(),
                    editstaff = $("#editstaff option:selected").text(),
                    editstaff_off = $("#editstaff option:selected").val();

                var data = {
                    start_city_id: editstart_city_id,
                    start_city_name: editstart_city_name,
                    start_address: editstart_address,
                    start_city_id_x: editstart_city_id_x,
                    end_city_id: editend_city_id,
                    end_city_name: editend_city_name,
                    end_address: editend_address,
                    end_city_id_x: editend_city_id_x,
                    bid_id:bid_id,
                  //  end_city_id2: editend_city_id+';'+editend_city_id2,
                 //  end_city_name2: editend_city_name+';'+editend_city_name2,
                   // end_address2: editend_address+';'+editend_address2,
                  //  end_city_id2_x:editend_city_id_x+';'+editend_city_id2_x,
                    start_bid_time: new Date(editstart_bid_time).getTime(),
                    end_bid_time: new Date(editend_bid_time).getTime(),
                    consignee_time: new Date(editconsignee_time).getTime(),
                    receipt_time: new Date(editreceipt_time).getTime(),
                    start_receipt_hour: editstart_receipt_hour,
                    end_receipt_hour: editend_receipt_hour,
                    danger: editdanger,
                    wuliu_type: editwuliu_type,
                    information: editinformation,
                    contacts: editcontacts,
                    contacts_phone: editcontacts_phone,
                    staff: editstaff,
                    remark:editremark,
                    staff_off: editstaff_off,
                    number: editnumber
                }
               
                $.ajax({
                    url: COMMONURL + "api/BidBase/UpdateBidBase?token=" + $.cookie('token'),
                    type: "post",
                    dataType: "json",
                    data: data,
                }).done(function(data) {
                	if(data.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;
                }
                    /* if(data.recode == '0000'){
                         $.blockUI({
                             message:redata.resmessage
                         });
                     }else{
                         $.blockUI({
                             message:redata.resmessage
                         });
                     }*/

                    if (data.recode == '0000') {
                        alert('操作成功');
                          
                          window.location.reload();
                    } else {
                        alert(data.resmessage);
                    }
                })
            }
        })
}
}
standard_tablistwm.init();
var timelist = setInterval(function(){standard_tablistwm.getList()},30000)  //
